<template>
  <div class="container">
    <a-card class="custom-card" title="">
      <a-row style="margin-bottom: 16px">
        <a-col :span="16">
          <a-space>
            <a-button v-if="!exportStatus" type="primary" status="warning" @click="batchExport()">
              <template #icon><icon-play-circle /></template>备份
            </a-button>
            <a-button v-else type="primary" status="warning" @click="batchExport()">
              备份完成，点击重新备份
            </a-button>
            <a-button status="success" @click="batchOptimize()">优化表</a-button>
            <a-button type="dashed" status="success" @click="batchRepair()">修复表</a-button>
          </a-space>
        </a-col>
        <a-col :span="8" style="text-align: right">

        </a-col>
      </a-row>
      <a-table
        row-key="name"
        :loading="loading"
        :pagination="false"
        :data="renderData"
        :bordered="{ wrapper: true, cell: true }"
        :row-selection="rowSelection"
        :scroll="tableScroll"
        column-resizable
        @selection-change="selectionChange"
      >
        <template #columns>
          <a-table-column title="序号" data-index="id" align="center" :width="70"/>
          <a-table-column title="表名" data-index="name" :width="200">
            <template #cell="{ record }">
              <a-link @click="view(record)">
                {{ record.name }}
              </a-link>
            </template>
          </a-table-column>
          <a-table-column title="表索引" data-index="engine" :width="100"/>
          <a-table-column title="数据量" data-index="rows" align="center" :width="100"/>
          <a-table-column title="数据大小" data-index="data_length" align="center" :width="100"/>
          <a-table-column title="碎片大小" data-index="data_free" align="center" :width="100"/>
          <a-table-column title="索引大小" data-index="index_length" align="center" :width="100"/>
          <a-table-column title="编码" data-index="collation" align="center" :width="170"/>
          <a-table-column title="创建时间" data-index="create_time" align="center" :width="180"/>
          <a-table-column title="说明" data-index="comment" align="center" :width="160"/>
          <a-table-column title="状态" data-index="status" align="center" :width="120">
            <template #cell="{ record }">
              <a-tag :class="`btn--${record.Name}`" color="">未备份</a-tag>
            </template>
          </a-table-column>
          <a-table-column title="操作" data-index="operations" align="center" fixed="right" :width="180">
            <template #cell="{ record }">
              <a-space>
                <a-button type="primary" size="small" @click="optimize([record])">优化表</a-button>
                <a-button type="primary" status="warning" size="small" @click="repair([record])">修复表</a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <View ref="viewRef"/>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, h, compile } from 'vue';
  import { useI18n } from 'vue-i18n';
  import { Message, Modal } from '@arco-design/web-vue';

  import useLoading from '@/hooks/loading';
  import screenHeight from '@/utils/screen-height';
  // import checkPermission from '@/utils/permission';
  import { ExportState, apiExportList, apiExport, apiOptimize, apiRepair } from '@/api/database';
  import View from './components/view.vue';

  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const height = screenHeight(265);
  const renderData = ref<ExportState[]>([]);
  const rowSelection = reactive({
    type: 'checkbox' as const,
    selectedRowKeys: [] as any,
    showCheckedAll: true,
  });
  const tableScroll = ref({
    x: '100%',
    y: height,
  });

  const isReset = ref(true); // 是否重置
  let selectionKeys: string[] = [] as string[]; // 选中项ID
  const viewRef = ref();
  const exportStatus = ref(false);

  // 列表
  const fetchData = async (params?: any) => {
    setLoading(true);
    reset();
    try {
      const { data } = await apiExportList(params);
      renderData.value = data.data;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 备份
  const doExport = (row: any[]) => {
    const title = '备份表';
    const message = `确定要备份选中的 <span style="color:red">${row.length} </span> 条数据吗？`;
    const tables = row;
    Modal.warning({
      title,
      content: () => h(compile(message)),
      closable: true,
      hideCancel: false,
      onOk: (async () => {
        setLoading(true);
        await apiExport({
          tables,
        }).then(res => {
          backup(res.data, row);
        }).catch(() => {
          setLoading(false);
        });

        window.onbeforeunload = function () {
          return '正在备份数据库，请不要关闭！';
        }
      }),
    });
  };
  // 优化表
  const optimize = (row: any[]) => {
    let title = '优化表';
    let message = `确定要优化选中的 <span style="color:red">${row.length} </span> 条数据吗？`;
    let tables = row;
    if (row.length === 1 && row[0].name) {
      title = `${title}：${row[0].name}`;
      message = `确定要优化表名 <span style="color:red">${row[0].name} </span> 这条数据吗？`;
      tables = [row[0].name];
    }
    Modal.warning({
      title,
      content: () => h(compile(message)),
      closable: true,
      hideCancel: false,
      onOk: (async () => {
        setLoading(true);
        try {
          const res: any = await apiOptimize({tables});
          if (res.status === 1) {
            Message.success(res.msg);
          }
        } catch (err) {
          setLoading(false);
        } finally {
          setLoading(false);
        }
      }),
    });
  };
  // 修复表
  const repair = (row: any[]) => {
    let title = '修复表';
    let message = `确定要修复选中的 <span style="color:red">${row.length} </span> 条数据吗？`;
    let tables = row;
    if (row.length === 1 && row[0].name) {
      title = `${title}：${row[0].name}`;
      message = `确定要修复表名 <span style="color:red">${row[0].name} </span> 这条数据吗？`;
      tables = [row[0].name];
    }
    Modal.warning({
      title,
      content: () => h(compile(message)),
      closable: true,
      hideCancel: false,
      onOk: (async () => {
        setLoading(true);
        try {
          const res: any = await apiRepair({tables});
          if (res.status === 1) {
            Message.success(res.msg);
          }
        } catch (err) {
          setLoading(false);
        } finally {
          setLoading(false);
        }
      }),
    });
  };
  // 备份
  const backup = async (data: any, row: any[]) => {
    // 开始备份
    if (data.status === 1) {
      document.getElementsByClassName(`btn--${data.tab.name}`)[0].innerHTML = '开始备份...(0%)';
      document.getElementsByClassName(`btn--${data.tab.name}`)[0].setAttribute('style', 'color: #ffffff; background-color: #86909c');
      await apiExport({
        id: data.tab.id,
        start: data.tab.start,
      }).then(res2 => {
        document.getElementsByClassName(`btn--${data.tab.name}`)[0].innerHTML = res2.data.info;
        document.getElementsByClassName(`btn--${data.tab.name}`)[0].setAttribute('style', 'color: #ffffff; background-color: #7bc616');
        if (res2.data.tab) {
          backup(res2.data, row);
        } else {
          exportStatus.value = true;
          setLoading(false);
          window.onbeforeunload = function () {
            return null;
          }
        }
      }).catch(() => {
        setLoading(false);
      });
    }
  };
  // 查看
  const view = async (row: any) => {
    viewRef.value.fetchData(row);
  };
  // 重置
  const reset = async () => {
    if (isReset.value) {
      rowSelection.selectedRowKeys = [];
      selectionKeys = [];
    } else {
      isReset.value = true;
    }
  };

  // 已选择的数据行发生改变时触发 -- table 表头
  const selectionChange = (rowKeys: any[]) => {
    rowSelection.selectedRowKeys = rowKeys;
    selectionKeys = rowKeys as string[];
  };
  const selectMsg = (message?: string) => {
    Message.info(message || '请选择需要操作的数据');
  };
  // 批量备份表
  const batchExport = () => {
    if (!selectionKeys.length) {
      selectMsg();
    } else {
      doExport(selectionKeys);
    }
  };
  // 批量优化表
  const batchOptimize = () => {
    if (!selectionKeys.length) {
      selectMsg();
    } else {
      optimize(selectionKeys);
    }
  };
  // 批量修复表
  const batchRepair = () => {
    if (!selectionKeys.length) {
      selectMsg();
    } else {
      repair(selectionKeys);
    }
  };

  fetchData();
</script>

<script lang="ts">
  export default {
    name: 'DatabaseExport',
  };
</script>

<style scoped lang="less">
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
</style>
